import { login, getUserInfo, getUserDetailById } from '@/api/user'
// import { removeToken } from '@/utils/auth'
const state = {
  token: localStorage.getItem('token') || '',
  userInfo: {} //
}

const mutations = {
  setToken(state, data) {
    // 储存到本地一直用
    localStorage.setItem('token', data)
    // 储存到state 马上用
    state.token = data
    // 把当前登入时间存入本地,方便主动检查超时
    localStorage.setItem('loginTime', Date.now())
  },
  getUserInfo(state, data) {
    state.userInfo = { ...data }
  },

  // 删除token
  removeToken(state) {
    state.token = ''
    //
    localStorage.removeItem('token')
  },
  // 清除数据
  removeUserInfo(state) {
    state.userInfo = {}
  }
}

const actions = {
  async login(store, data) {
    // 发送请求  获取登入数据
    const res = await login(data)
    //
    store.commit('setToken', res)
    // console.log(16, res)
    // console.log(17, '登入成功')
  },

  // 发送请求  用户信息
  async getUserInfo(store) {
    const res = await getUserInfo()
    // 数据不够再发送一个请求,拿头像图片
    const datail = await getUserDetailById(res.userId)
    store.commit('getUserInfo', {
      ...res,
      ...datail
    })
    // console.log(30, res)
    // console.log(39, datail)
  },

  logout(store) {
    store.commit('removeToken')
    store.commit('removeUserInfo')
  }
}

// 导出
export default {
  // 严格模式
  namespaced: true,
  state,
  mutations,
  actions
}
